package com.freesky.quartz.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.freesky.biz.activity.mapper.AlipayBillTaskMapper;
import com.freesky.biz.pay.service.SinopecService;
import com.freesky.biz.rights.domain.RightsSinopecDataEntity;
import com.freesky.biz.rights.domain.RightsSinopecTaskEntity;
import com.freesky.biz.rights.mapper.RightsSinopecDataMapper;
import com.freesky.biz.rights.service.IRightsSinopecDataService;
import com.freesky.biz.rights.service.IRightsSinopecTaskService;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.config.Constant;
import com.freesky.common.config.ProjectConfig;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.utils.StringUtils;
import com.freesky.framework.web.service.SendAlarmService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 中石化权益核销
 */
@Slf4j
@Component("rightsSinopecConsumeTask")
public class RightsSinopecConsumeTask {
    @Autowired
    private IRightsSinopecTaskService rightsSinopecTaskService;

    @Autowired
    private SinopecService sinopecService;
    
    @Autowired
    private IRightsSinopecDataService rightsSinopecDataService;

    @Autowired
    private AlipayBillTaskMapper alipayBillTaskMapper;

    @Autowired
    private SendAlarmService sendAlarmService;

    private DateTime minDateTime = DateUtil.parse("2025-06-24","yyyy-MM-dd");

    ///alidata/java_app/manager/uploadPath/download//sinopec/2025-08-25.txt
    public void taskProcess() {
        DateTime yesterday = DateUtil.offsetDay(new Date(), -1);
        DateTime startTime;
        RightsSinopecTaskEntity latestBillTask = rightsSinopecTaskService.selectLatestTask();
        if(latestBillTask==null){
            startTime = minDateTime;
        } else {
            log.info("endTIme:"+latestBillTask.getStartDay());
            startTime = DateUtil.parse(latestBillTask.getStartDay(),"yyyy-MM-dd");
        }
        log.info("startTime:"+DateUtil.format(startTime,"yyyy-MM-dd"));
        int generalNum = 0;
        while(startTime.isBefore(yesterday)){
            RightsSinopecTaskEntity rightsSinopecTask = new RightsSinopecTaskEntity();
            rightsSinopecTask.setId(SeqUtil.getSeqId());

            startTime = DateUtil.offsetDay(startTime, 1);
            String billQryStartTime = DateUtil.format(startTime,"yyyy-MM-dd");

            if(startTime.isAfter(yesterday)){
                log.info("startTime is After yesterday:"+billQryStartTime);
                break;
            }

            String billQryEndTime = "";
            startTime = DateUtil.offsetDay(startTime,1);
            if(startTime.isAfter(yesterday)){
                billQryEndTime = DateUtil.format(yesterday,"yyyy-MM-dd");
            } else {
                billQryEndTime = DateUtil.format(startTime,"yyyy-MM-dd");
            }
            rightsSinopecTask.setStartDay(billQryEndTime);

            AjaxResult ajaxResult = createDailyBill(rightsSinopecTask.getStartDay());
            if(!ajaxResult.isSuccess()){
                sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】JOB-中石化权益核销",ajaxResult.getMsg());
                break;
            }
            Map<String,Object> respMap = (Map<String,Object>)ajaxResult.get("data");
            String remoteFilePath = respMap.get("remotePath").toString();
            if(StringUtils.isNotEmpty(remoteFilePath)) {
                ajaxResult = downloadDailyBill(rightsSinopecTask.getStartDay(), remoteFilePath);
                if (!ajaxResult.isSuccess()) {
                    sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL, "【异常】JOB-中石化权益核销", ajaxResult.getMsg());
                    break;
                }
            }
            rightsSinopecTask.setFilePath(remoteFilePath);
            rightsSinopecTask.setProcessed("2");
            rightsSinopecTask.setCreateDate(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            rightsSinopecTask.setUpdateDate(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            rightsSinopecTask.setDelFlag("0");
            rightsSinopecTaskService.addRightsSinopecTask(rightsSinopecTask);
            generalNum = generalNum + 1;
        }
        //更新核销数据
        alipayBillTaskMapper.updateSinopecConsumeStatus();
    }

    public AjaxResult createDailyBill(String startDay) {
        return sinopecService.crmPackageReport(startDay);
    }

    public AjaxResult downloadDailyBill(String day,String downloadUrl){
        try {
            String downloadPath = ProjectConfig.getDownloadPath() + "/sinopec/" + day + ".txt";
            log.info("downloadPath:" + downloadPath);
            File downloadFile = new File(downloadPath);
            downloadFile.deleteOnExit();;
            HttpUtil.downloadFile(downloadUrl, downloadFile);
            if (!downloadFile.exists()) {
                return AjaxResult.error("下载失败");
            }
            List<String> lines = FileUtil.readLines(downloadFile, StandardCharsets.UTF_8);
            List<RightsSinopecDataEntity> dataList = new ArrayList<>();
            for (String line : lines) {
                String[] parts = line.split("\\|");
                if (parts.length >= 8) {
                    RightsSinopecDataEntity entity = new RightsSinopecDataEntity();
                    entity.setId(SeqUtil.getSeqId());
                    entity.setActivityCode(parts[0]);
                    entity.setActivityName(parts[1]);
                    entity.setPackageName(parts[2]);
                    entity.setWriteOff(parts[3]);
                    entity.setVoucherStatus(parts[4]);
                    entity.setTicketNo(parts[5]);
                    entity.setOutSn(parts[6]);
                    entity.setApplyTime(parts[7]);
                    entity.setCreateDate(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                    entity.setUpdateDate(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                    entity.setDelFlag("0");
                    dataList.add(entity);
                    // 每5000条批量插入一次
                    if (dataList.size() >= 5000) {
                        rightsSinopecDataService.saveBatch(dataList);
                        dataList.clear();
                    }
                }
            }
            // 插入剩余数据
            if (!dataList.isEmpty()) {
                rightsSinopecDataService.saveBatch(dataList);
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            return AjaxResult.error(ioe.getMessage());
        }
        return AjaxResult.success();
    }

 }
